import common from "@/common/common.js";

function saveToken(token) {
	uni.setStorageSync('token', token)
}

function login(res) {
	//缓存
	saveCache(res);
	//初始化IM
	getApp().loginIM();
	// iswanshan: 1.首页；其他：注册流程
	if (res.data.user.iswanshan == 2) {
		uni.navigateTo({
			url: '/main/register/register-info',
			fail: (error) => {
				uni.showToast({
					title: JSON.stringify(error),
					icon: 'none'
				})
			}
		})
	} else {
		uni.setStorageSync('login', true);
		uni.switchTab({
			url: '/pages/tab/home/home',
			fail: (error) => {
				uni.showToast({
					title: JSON.stringify(error),
					icon: 'none'
				})
			}
		})
		//第一次登录
		uni.$emit("requestHome");
	}
}

function loginOnce() {
	uni.reLaunch({
		url: '/main/login/login'
	})
}

function logout() {
	uni.reLaunch({
		url: '/main/login/login',
	});
	//清空缓存：token, 登录状态
	clearCache();
	try {
		//IM退出:在App.vue中第一次登录会报错
		uni.$TUIKit.logout();
	} catch (error) {
		console.log("IM退出失败: " + JSON.stringify(error));
	}
}

 async function wxLogin(openId){
	let param = {
		loginname: openId,
		code:'708090',
		loginType:2
	};
	let res = await common.post('/api/login', param);
	if (0 == res.code) {
		saveToken(res.data.token)
		login(res)
	} else {
		common.showToast(res.message)
	}
}


function saveCache(res) {
	uni.setStorageSync('userId', res.data.user.id);
	uni.setStorageSync('userName', res.data.user.nick);
	uni.setStorageSync('userPic', res.data.user.pic);
	uni.setStorageSync('userSex', res.data.user.sex);
	uni.setStorageSync('userTxCode', res.data.user.tengxuncode);
	uni.setStorageSync('userLoginname', res.data.user.loginname);
}

function clearCache() {
	uni.removeStorageSync('login');
	uni.removeStorageSync('token');
	getApp().globalData.openTicketMin = false
}

export default {
	saveToken,
	login,
	logout,
	loginOnce,
	wxLogin
}